#! -*- coding:utf-8 -*-

import time

from django.core.management.base import BaseCommand

from common import orm
from common.lottery import METIS_GAME_TYPE
from common.platform.metis.handler import add_bet_logs_by_game
from common.utils import track_logging
from common.utils.thread import GracefulExitedExecutor, Thread

_LOGGER = track_logging.getLogger(__name__)

game_list = [
    METIS_GAME_TYPE.DRAGON_TIGER, METIS_GAME_TYPE.SUPER_SIX, METIS_GAME_TYPE.GOLD_SHARK, METIS_GAME_TYPE.SUPER_BULL
]


class Command(BaseCommand):

    def handle(self, **kwargs):
        GracefulExitedExecutor('Sync Metis Data Processor', [SyncGameDataTask(game) for game in game_list]).start()


class SyncGameDataTask(Thread):
    def __init__(self, game):
        Thread.__init__(self)
        self.game = game

    def run(self):
        while not self.shutdown_flag.is_set():
            success = True
            try:
                add_bet_logs_by_game(self.game)
            except:
                success = False
                _LOGGER.exception('sync metis data error')
            finally:
                orm.session.close()
                if not success:
                    time.sleep(10)
